package com.goparry.taskman.restclient;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.res.Resources;
import android.util.Xml;

import com.goparry.taskman.repository.*;

public class XmlPullTasksParser {

	XmlPullParser xpp;

	public XmlPullTasksParser(String UrlString) {
		xpp = Xml.newPullParser();
		try {
			URL url= new URL(UrlString);
			xpp.setInput(url.openConnection().getInputStream(), null) ; 
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
	}
	
	public XmlPullTasksParser(Resources resources, int id) {
		xpp = resources.getXml(id);
	}
	
	public List<Task> parse() {
		List<Task> tasks = null;
		String xmlString = "";
		
		try {
			int eventType = xpp.getEventType();
			Task currentTask = null;
			Boolean done = false;
			while (eventType != XmlPullParser.END_DOCUMENT && !done) {
				String name = null;
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					tasks = new ArrayList<Task>();
					break;
				case XmlPullParser.START_TAG:
					name = xpp.getName();
					if (name.equalsIgnoreCase("Task")) {
						currentTask = new Task();
					} else if (currentTask != null) {
						if (name.equalsIgnoreCase("Name")) {
							currentTask.setName(xpp.nextText());
						} else if (name.equalsIgnoreCase("Title")) {
							currentTask.setTitle(xpp.nextText());
						} else if (name.equalsIgnoreCase("Type")) {
							currentTask.setType(xpp.nextText());
						} else if (name.equalsIgnoreCase("Instructions")) {
							currentTask.setInstructions(xpp.nextText());
						} else if (name.equalsIgnoreCase("Step")) {
							currentTask.setStep(xpp.nextText());
						} else if (name.equalsIgnoreCase("ReceivedDate")) {
							currentTask.setReceivedDate(xpp.nextText());
						} else if (name.equalsIgnoreCase("DueDate")) {
							currentTask.setDueDate(xpp.nextText());
						}else if (name.equalsIgnoreCase("Documents")) {
							currentTask.setDocumentIDs(xpp.nextText());
						}
					}
					break;
				case XmlPullParser.END_TAG:
					name = xpp.getName();
					if (name.equalsIgnoreCase("Task") && currentTask != null) {
						currentTask.setDocuments(xmlString);
						tasks.add(currentTask);
					} else if (name.equalsIgnoreCase("Task")) {
						done = true;
					}
					break;
				}
				eventType = xpp.next();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return tasks;
	}
}
